﻿using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Dotnet.Utils.Utility.Dependency.Autofac
{
    public sealed class LazyService
    {
        private readonly ILifetimeScope _container;

        public LazyService(ILifetimeScope container)
        {
            _container = container;
        }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetService<T>() where T : notnull
        {
            return _container.Resolve<T>();
        }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public object GetService(Type type)
        {
            return _container.Resolve(type);
        }

        /// <summary>
        /// 获取实例(一对多)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetService<T>(Type type) where T : notnull
        {
            return GetServices<T>().FirstOrDefault(a => a.GetType().Equals(type)) ?? _container.Resolve<T>();
        }

        /// <summary>
        /// 获取实例列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IEnumerable<T> GetServices<T>() where T : notnull
        {
            return _container.Resolve<IEnumerable<T>>();
        }
    }
}